package cn.com.sinux.spring.exception;


import java.io.PrintStream;
import java.io.PrintWriter;

/**
 * Created by Administrator on 2015/8/26.
 */
public class BaseException extends RuntimeException {
    protected Throwable cause;

    public BaseException() {
        super();
    }

    public BaseException(Throwable nested) {
        this.cause = nested;
    }

    public BaseException(String msg) {
        super(msg);
    }

    public BaseException(String msg, Throwable ex) {
        super(msg);
        this.cause = ex;
    }

    public Throwable getCause() {
        return (this.cause == this ? null : this.cause);
    }

    public String getMessage() {
        String message = super.getMessage();
        Throwable cause = getCause();
        if (cause != null) {
            return message + "; nested exception is " + cause;
        }
        return message;
    }

    public void printStackTrace(PrintStream ps) {
        if (getCause() == null) {
            super.printStackTrace(ps);
        } else {
            ps.println(this);
            ps.print("Caused by: ");
            getCause().printStackTrace(ps);
        }
    }

    public void printStackTrace(PrintWriter pw) {
        if (getCause() == null) {
            super.printStackTrace(pw);
        } else {
            pw.println(this);
            pw.print("Caused by: ");
            getCause().printStackTrace(pw);
        }
    }

    public Throwable getRootCause() {
        Throwable cause = getCause();
        if (cause instanceof BaseException) {
            return ((BaseException) cause).getRootCause();
        } else {
            return cause;
        }
    }

    public boolean contains(Class exClass) {
        if (exClass == null) {
            return false;
        }
        if (exClass.isInstance(this)) {
            return true;
        }
        Throwable cause = getCause();
        if (cause instanceof BaseException) {
            return ((BaseException) cause).contains(exClass);
        } else {
            return (cause != null && exClass.isInstance(cause));
        }
    }

}
